/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pv168.uloha3.swing.workers;

import cz.muni.fi.pv168.uloha3.common.DBUtils;
import cz.muni.fi.pv168.uloha3.entities.RealEstate;
import cz.muni.fi.pv168.uloha3.entities.RealEstateType;
import cz.muni.fi.pv168.uloha3.exceptions.RealEstateManagerException;
import cz.muni.fi.pv168.uloha3.managers.RealEstateManager;
import cz.muni.fi.pv168.uloha3.managers.impl.RealEstateManagerImpl;
import cz.muni.fi.pv168.uloha3.swing.EstatesTableModel;
import cz.muni.fi.pv168.uloha3.swing.SwingGuiMain;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author stefan
 */
public class EstateAddSwingWorker extends SwingWorker<RealEstate, Void> {

    private final String catastralID;
    private final String address;
    private final String type;
    private final EstatesTableModel model;
    
    public EstateAddSwingWorker(String catastralID, String address, String type, EstatesTableModel model) { 
        this.catastralID = catastralID;
        this.address = address;
        this.type = type;
        this.model = model;
    }

    @Override
    protected RealEstate doInBackground() throws Exception {
        
        DataSource dataSource = DBUtils.initConnector();
        
        RealEstateManager managerEstate = new RealEstateManagerImpl();
        managerEstate.setDataSource(dataSource);
        
        RealEstate newEstate = new RealEstate();
        newEstate.setCatastralId(catastralID);
        newEstate.setAddress(address);
        newEstate.setType(RealEstateType.fromValue(type));

        try {
            managerEstate.addRealEstate(newEstate);
        } catch (RealEstateManagerException ex) {
            Logger.getLogger(SwingGuiMain.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Estate could not be created (" + ex.getMessage() + ")");
        }
        
        model.addEstate(newEstate);
        JOptionPane.showMessageDialog(null, "Estate added");
        return newEstate;
    }
}
